package com.ken.astroboy.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Repository
public class MyInterceptor implements HandlerInterceptor {

    //private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        
        String reqUri = request.getRequestURI();
        String contextPath = request.getContextPath();
        String referer = request.getHeader("referer");
        
        //logger.info("reqUri: {}", reqUri);
        //logger.info("contextPath: {}", contextPath);
        //logger.info("referer: {}", referer);
        
        //当url地址为登录的url的时候跳过拦截器  
        if((contextPath + "/login").equals(reqUri) || (contextPath + "/").equals(reqUri) 
               || (contextPath + "/index.html").equals(reqUri) ){              
            return true; 
        }else{  

            if(referer != null || (contextPath + "/panel").equals(reqUri)){
                
                HttpSession session = request.getSession();  
    
                Object obj = session.getAttribute("user");
    
                if( (obj == null) || (StringUtils.isBlank(obj.toString())) ){     
                    StringBuilder sb = new StringBuilder();
                    
                    sb.append(request.getScheme())
                    .append("://")
                    .append(request.getServerName())
                    .append(":")
                    .append(request.getServerPort())
                    .append("/");
        
                    if(StringUtils.isNotBlank(request.getContextPath())){
                        sb.append(request.getContextPath()).append("/");
                    }
                        
                    sb.append("login");
                    
                    response.sendRedirect(sb.toString());   
                    
                    return false;
                }                
            }else{
                return false;
            }
        } 
        return true; 
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }


}
    